<template>
  <div>
    <AModal
      v-bind="$attrs"
      width="800px"
      :body-style="{ padding: '0px' }"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AScrollbar style="max-height: calc(100vh - 170px); overflow: auto; padding: 20px">
        <AForm ref="formRef" :model="form" auto-label-width>
          <ARow :gutter="10">
            <ACol :span="12">
              <AFormItem
                field="deliveryOrderId"
                label="送货单"
                :rules="[{ required: true, message: '请输入客户名称' }]"
                :validate-trigger="['change', 'input', 'blur']"
              >
                <ASelect
                  v-model="form.deliveryOrderId"
                  placeholder="送货单"
                  allow-search
                  @change="deliveryChange"
                >
                  <AOption
                    v-for="(item, index) in deliveryOrderList"
                    :key="index"
                    :label="item.deliveryOrderCode"
                    :value="item.deliveryOrderId"
                  ></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem
                field="customerId"
                label="所属客户"
                :rules="[{ required: true, message: '请输入客户名称' }]"
                :validate-trigger="['change', 'input', 'blur']"
              >
                <ASelect v-model="form.customerId" placeholder="所属客户" allow-search>
                  <AOption
                    v-for="(item, index) in companyList"
                    :key="index"
                    :label="item.customerName"
                    :value="item.customerId"
                  ></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol>
              <AFormItem field="remark" label="备注">
                <ATextarea v-model="form.remark" placeholder="备注"></ATextarea>
              </AFormItem>
            </ACol>
          </ARow>
          <ACard
            v-for="(item, index) in form.detailList"
            :key="index"
            class="card-container"
            size="small"
          >
            <ARow :gutter="10">
              <ACol :span="12">
                <AFormItem field="materialName" label="产品名称">
                  {{ item.materialName }}
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="spec" label="规格">
                  {{ item.spec }}
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="unit" label="单位">
                  {{ item.unit }}
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="unitPrice" label="单价">
                  {{ decimalRound(item.unitPrice, 4) }}
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="qty" label="数量">
                  <AInputNumber
                    v-model="item.qty"
                    model-event="input"
                    placeholder="数量"
                    hide-button
                    :precision="0"
                    :step="1"
                    @change="inputEvent('qty', item)"
                  />
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="amt" label="金额">
                  <div>{{ `¥${formatPrice(item.amt || 0)}` }}</div>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="processResult" label="处理结果">
                  <AInput v-model="item.processResult" placeholder="处理结果" />
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="questionDesc" label="反馈问题">
                  <AInput v-model="item.questionDesc" placeholder="反馈问题" />
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="processSuggestion" label="处理意见">
                  <AInput v-model="item.processSuggestion" placeholder="处理意见" />
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="directorBy" label="责任人">
                  <AInput v-model="item.directorBy" placeholder="责任人" />
                </AFormItem>
              </ACol>
            </ARow>
          </ACard>
        </AForm>
      </AScrollbar>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import { Message } from '@arco-design/web-vue'
import { CustomerResItem, getCustomerAllList } from '@renderer/api/company'
import { formatPrice } from '@renderer/utils/mixins'
import {
  DeliveryResItem,
  editReturnReissue,
  getDeliveryAllList,
  getReturnReissueDetail,
  ReturnReissueReq,
  ReturnReissueResItem
} from '@renderer/api/logisticsDep'
import { useMenuState } from '@renderer/store'
import { getArrayItemType } from '@renderer/types/global'
import { deleteNullObject } from '@renderer/utils/data-processing'
import { decimalRound } from '@renderer/utils/mixins'

interface Props {
  [key: string]: any
  checkData?: Partial<ReturnReissueResItem>
}
const props = withDefaults(defineProps<Props>(), {
  checkData: () => {
    return {}
  }
})
const emit = defineEmits(['update:visible', 'reload'])
const attrs = useAttrs()
const formRef = ref()
const form = ref<ReturnReissueReq>({
  deliveryOrderId: '',
  deliveryOrderCode: '',
  customerId: '',
  customerName: '',
  isInclTax: 0,
  directorBy: '',
  remark: '',
  detailList: []
})
const companyList = ref<CustomerResItem[]>([])
const deliveryOrderList = ref<DeliveryResItem[]>([])
const menuParam = useMenuState()

// 获取客户列表
const getCompanyList = () => {
  getCustomerAllList({
    customerName: '',
    taxNo: '',
    contactName: ''
  }).then((res) => {
    companyList.value = res.data.list
  })
}
// 获取送货单列表
const getDeliveryList = () => {
  getDeliveryAllList({ deliveryOrderCode: '', isVoid: 0 }).then((res) => {
    deliveryOrderList.value = res.data.list
  })
}
const getDetail = () => {
  getReturnReissueDetail({ returnReissueId: props.checkData.returnReissueId! }).then((res) => {
    form.value = res.data
  })
}

// 弹窗事件
const modalEvent = (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate((errors: any) => {
        if (!errors) {
          // 新增
          if ((attrs.title as string).includes('新增')) {
            form.value.returnReissueId = undefined
          }
          const tempCom = companyList.value.find(
            (item) => item.customerId === form.value.customerId
          )
          const tempDelivery = deliveryOrderList.value.find(
            (item) => item.deliveryOrderId === form.value.deliveryOrderId
          )
          if (tempCom) {
            form.value.customerName = tempCom.customerName
          }
          if (tempDelivery) {
            form.value.deliveryOrderCode = tempDelivery.deliveryOrderCode!
          }

          editReturnReissue(deleteNullObject(form.value)).then(() => {
            Message.success((attrs.title as string).includes('新增') ? '新增成功' : '修改成功')
            modalEvent('cancel')
            emit('reload')
          })
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      emit('update:visible', false)
      break
    case 'open':
      getCompanyList()
      getDeliveryList()
      if ((attrs.title as string).includes('修改')) {
        getDetail()
      }
      menuParam.switchEditStatus(true)
      break
    case 'cancel':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      form.value = {
        deliveryOrderId: '',
        deliveryOrderCode: '',
        customerId: '',
        customerName: '',
        isInclTax: 0,
        directorBy: '',
        remark: '',
        detailList: []
      }
      emit('update:visible', false)
      break
    default:
      break
  }
}

const deliveryChange = () => {
  const tempItem = deliveryOrderList.value.find(
    (item) => item.deliveryOrderId === form.value.deliveryOrderId
  )
  if (tempItem) {
    form.value.detailList = tempItem.detailList.map((item) => {
      return {
        ...item,
        questionDesc: '',
        returnProcess: '',
        processResult: '',
        processSuggestion: '',
        directorBy: ''
      }
    })
  }
}

const inputEvent = (
  type: 'qty' | 'unitPrice',
  paramsItem: getArrayItemType<ReturnReissueReq['detailList']>
) => {
  switch (type) {
    case 'qty':
      paramsItem.amt = Number(decimalRound(paramsItem.qty! * paramsItem.unitPrice!, 4))
      break
    case 'unitPrice':
      paramsItem.amt = Number(decimalRound(paramsItem.qty! * paramsItem.unitPrice!, 4))
      break
    default:
      break
  }
}
</script>
<style scoped>
.card-container {
  margin-bottom: 10px;
}
</style>
